import React, { useState, useEffect } from 'react'
import axios from 'axios'
const useFetchData = (initialUrl, initialData) => {
    const [url, setUrl] = useState(initialUrl)
    const [data, setData] = useState(initialData)
    const [isLoading, setIsLoading] = useState(false)
    const [isError, setIsError] = useState(false)
    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true)
            setIsError(false)
            try {
                const ret = await axios(url)
                setData(ret.data.data)
            } catch (e) {
                setIsError(true)
            }
            setIsLoading(false)
        }
        fetchData()
    }, [url])
    return [{ data, isLoading, isError }, setUrl]
}
export default function () {
    const [query, setQuery] = useState('')
    const [{ data, isLoading, isError }, doFetch] = useFetchData('http://wthrcdn.etouch.cn/weather_mini?city=青岛', null)
    return (
        <div>
            <h2>使用自定义hooks，并封装为公用</h2>
            <p>输入内容后可直接按回车</p>
            <form onSubmit={(e) => { e.preventDefault(); doFetch('http://wthrcdn.etouch.cn/weather_mini?city=' + query) }}>
                <input value={query} onChange={e => setQuery(e.target.value)} />
                <button type='submit'>搜索</button>
            </form>

            {isError && <div style={{ background: 'pink', padding: '1rem', margin: '1rem' }}>出错啦~~</div>}

            {data && (isLoading
                ? <div> loading...</div>
                : <>
                    <p><strong>城市：</strong>{data.city}</p>
                    <p><strong>当前温度：</strong>{data.wendu}℃</p>
                    <p><strong>感冒预警：</strong>{data.ganmao}</p>
                    <h4>未来{data.forecast?.length}天天气情况</h4>
                    <ul>
                        {data.forecast?.length
                            ? data.forecast.map(item => <li key={item.date}>{`${item.date} - ${item.type} - ${item.low}~${item.high}`}</li>)
                            : null}
                    </ul>
                </>)}

        </div>
    )
}
